package org.jmh.gift.service.impl;

import org.jmh.gift.domain.GoodsSku;
import org.jmh.gift.mapper.GoodsSkuMapper;
import org.jmh.gift.service.IGoodsSkuService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Iterator;
import java.util.Map;

/**
 * <p>
 * sku表 服务实现类
 * </p>
 *
 * @author lingfeng
 * @since 2024-07-30
 */
@Service
public class
GoodsSkuServiceImpl extends ServiceImpl<GoodsSkuMapper, GoodsSku> implements IGoodsSkuService {

    @Autowired
    private GoodsSkuMapper goodsSkuMapper;

    /**
     * 可用库存=不变  锁定库存=锁定库存+本次用户购买的量
     * @param skuInfos
     */
    @Override
    @Transactional
    public void lockStock(Map<Long, Integer> skuInfos) {
        // 一次性可以买多个商品，且每个商品购买的数量是不一样的
        Iterator<Map.Entry<Long, Integer>> iterator = skuInfos.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<Long, Integer> skuInfo = iterator.next();
            Long skuId = skuInfo.getKey();
            Integer num = skuInfo.getValue();
            goodsSkuMapper.lockStock(skuId,num);
        }
    }

    /**
     * 用户超时未支付取消
     * 可用库存不变  锁定库存 = 锁定库存 - 本次用户购买的数量
     * @param skuInfos
     */
    @Override
    public void subLockStock(Map<Long, Integer> skuInfos) {
        Iterator<Map.Entry<Long, Integer>> iterator = skuInfos.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<Long, Integer> skuInfo = iterator.next();
            Long skuId = skuInfo.getKey();
            Integer num = skuInfo.getValue();
            goodsSkuMapper.subLockStock(skuId,num);
        }
    }
}
